package com.baidu.iit.pxp.listener;

import com.baidu.iit.pvm.ActivityIllegalArgumentException;
import com.baidu.iit.pxp.event.ActivityEvent;
import com.baidu.iit.pxp.util.ReflectUtil;

/**
 * User: huangweili
 * Date: 14-4-30
 * Time: 下午3:55
 */
public class DelegateActivitiEventListener extends BaseDelegateEventListener {

    protected String className;
    protected ActivityEventListener delegateInstance;
    protected boolean failOnException = true;

    public DelegateActivitiEventListener(String className, Class<?> entityClass) {
        this.className = className;
        setEntityClass(entityClass);
    }

    @Override
    public void onEvent(ActivityEvent event) {
        if(isValidEvent(event)) {
            getDelegateInstance().onEvent(event);
        }
    }

    @Override
    public boolean isFailOnException() {
        if(delegateInstance != null) {
            return delegateInstance.isFailOnException();
        }
        return failOnException;
    }

    protected ActivityEventListener getDelegateInstance() {
        if(delegateInstance == null) {
            Object instance = ReflectUtil.instantiate(className);
            if(instance instanceof ActivityEventListener) {
                delegateInstance = (ActivityEventListener) instance;
            } else {
                // Force failing of the listener invocation, since the delegate cannot be created
                failOnException = true;
                throw new ActivityIllegalArgumentException("Class " + className
                        + " does not implement " + ActivityEventListener.class.getName());
            }
        }
        return delegateInstance;
    }
}
